package com.weakteam.orderonline.adminconsole.gwt.client.widget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.*;
import com.weakteam.orderonline.adminconsole.gwt.client.domain.Place;
import com.weakteam.orderonline.adminconsole.gwt.client.util.WebContext;


/**
 * Created by Max on 08.04.2014 for OrderOnline.
 */
public class PlacesPopup extends DialogBox implements HasValueChangeHandlers<Place> {

    interface TablesPopupUiBinder extends UiBinder<Widget, PlacesPopup> { }
    private static TablesPopupUiBinder uiBinder = GWT.create(TablesPopupUiBinder.class);

    @UiField  protected TextBox nameInput;
    @UiField  protected Image qrcodeImage;
    @UiField  protected Button cancelButton;
    @UiField  protected Button approveButton;
    private Place place;

    public PlacesPopup(Place place) {
        setWidget(uiBinder.createAndBindUi(this));
        this.setAnimationEnabled(true);
        this.setGlassEnabled(true);
        this.addStyleName("places-popup");
        // add handlers
        this.cancelButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                PlacesPopup.this.hide();
            }
        });
        this.approveButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                ValueChangeEvent.fire(PlacesPopup.this, getInputTable());
                PlacesPopup.this.hide();
            }
        });
        //
        this.place = place;
        String name = place.getName();
        if (name==null) {
            name="";
            this.setText("Добавление стола");
        } else {
            this.setText("Редактирование стола");
        }
        this.nameInput.setText(name);
        String qrText = "{\"ip\":\"81.177.48.54\",\"port\":\"8080\",\"customerId\":\"TestRest\",\"placeId\":"+place.getId()+"}";
        this.qrcodeImage.setUrl(WebContext.getInstance().getRootContext() + "getQRCodeImage?qrText="+ qrText);
        // show
        this.center();
        this.show();
    }

    @Override
    public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Place> handler) {
        return super.addHandler(handler, ValueChangeEvent.getType());
    }

    private Place getInputTable() {
        place.setName(this.nameInput.getText());
        return this.place;
    }

}
